# -*- coding: utf-8 -*-

#    OriginDB
#    Copyright (C) 2010  Jason Power <power.jg@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4 import QtCore
from PyQt4.QtGui import *

from editorScene import EditorScene
from toolBoxes import ToolWidget, ItemWidget

from ui_editorWindow import Ui_EditorWindow

import pybel

class EditorWindow(QMainWindow):
	def __init__(self, controller, mol=None, callback=None, parent=None):
		QMainWindow.__init__(self, parent)

		self.controller = controller
		self.callback = callback

		self.ui = Ui_EditorWindow()
		self.ui.setupUi(self)

		self.editMenu = QMenu("Edit", self)
		self.ui.menubar.addMenu(self.editMenu)

		self.mainScene = EditorScene(mol)
		self.mainView = QGraphicsView(self.mainScene)

		self.undoAction = QAction("Undo", self)
		self.undoAction.setShortcut(QKeySequence.Undo)
		self.redoAction = QAction("Redo", self)
		self.redoAction.setShortcut(QKeySequence.Redo)

		self.editMenu.addAction(self.undoAction)
		self.editMenu.addAction(self.redoAction)

		#self.connect(self.undoAction, QtCore.SIGNAL("triggered()"), self.mainScene.undoStack.undo)
		#self.connect(self.redoAction, QtCore.SIGNAL("triggered()"), self.mainScene.undoStack.redo)
		
		self.setCentralWidget(self.mainView)

		self.tools = ToolWidget(self.mainScene, self)
		self.items = ItemWidget(self.mainScene, self)

		self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.tools)
		self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.items)

	def closeEvent(self, event):
		if self.callback:
			if self.maybeCallback():
				event.accept()
			else:
				event.ignore()
		else:
			if self.maybeSave():
				event.accept()
			else:
				event.ignore()


	def maybeCallback(self):
		box = QMessageBox(self)
		box.addButton(QMessageBox.Yes)
		box.addButton(QMessageBox.Discard)
		box.addButton(QMessageBox.Cancel)
		box.setWindowTitle("Leave compound editor?")
		box.setText("Do you want to export the compound back to OriginDB?")

		ret = box.exec_()

		if ret == QMessageBox.Yes:
			self.callback(pybel.Molecule(self.mainScene.getMol()))
			return True
		elif ret == QMessageBox.Discard:
			return True
		else:
			return False